# -*- coding: utf-8 -*-
"""
Created on Thu Jun 16 20:24:50 2016

@author: Yin Qiaonan
"""

from math import log
import operator

def createDataSet():
    dataSet = [[1, 1, 'yes'],
               [1, 1, 'yes'],
               [1, 0, 'no'],
               [0, 1, 'no'],
               [0, 1, 'no']]
    labels = ['no surfacing', 'flippers']
    return dataSet, labels

def calcShannonEnt(dataSet):
    numEntries = len(dataSet)     #entries number
    labelCounts = {}     #recording numbers of labels 'Yes' and 'No'
    for featVec in dataSet:
        currentLabel = featVec[-1]     #labels 'Yes' or 'No'
        if currentLabel not in labelCounts.keys():     #first appearance of each label
            labelCounts[currentLabel] = 0
        labelCounts[currentLabel] += 1
    shannonEnt = 0.0
    for key in labelCounts:
        prob = float(labelCounts[key])/numEntries
        shannonEnt -= prob * log(prob, 2)     #entropy
    return shannonEnt

def splitDataSet(dataSet, axis, value):
    retDataSet = []
    for featVec in dataSet:
        if featVec[axis] == value:     #cutting out the feature splitting on
            reducedFeatVec = featVec[:axis]
            reducedFeatVec.extend(featVec[axis + 1:])
            retDataSet.append(reducedFeatVec)
    return retDataSet

def chooseBestFeatureToSplit(dataSet):
    numFeatures = len(dataSet[0]) - 1     #features number
    baseEntropy = calcShannonEnt(dataSet)     #entrpoy of dataSet
    bestInfoGain = 0.0
    bestFeature = -1
    for i in range(numFeatures):     #for each feature
        featList = [example[i] for example in dataSet]     #list of values of a feature
        uniqueVals = set(featList)     #remove duplicates
        newEntropy = 0.0
        for value in uniqueVals:     #split according to each value of a feature
            subDataSet = splitDataSet(dataSet, i, value)     #splitted dataSet
            prob = len(subDataSet)/float(len(dataSet))
            newEntropy += prob * calcShannonEnt(subDataSet)     #combined entropy of a split
        infoGain = baseEntropy - newEntropy     #information gain of a split
        if (infoGain > bestInfoGain):     #find the best split
            bestInfoGain = infoGain
            bestFeature = i
    return bestFeature

def majorityCnt(classList):
    classCount = {}
    for vote in classList:
        if vote not in classCount.keys():
            classCount[vote] = 0
        classCount[vote] += 1
    sortedClassCount = sorted(classCount.items(), key = operator.itemgetter(1), reverse = True)
    return sortedClassCount[0][0]

def createTree(dataSet, labels):
    classList = [example[-1] for example in dataSet]     #list of values of labels
    if classList.count(classList[0]) == len(classList):     #all belong to only one label
        return classList[0]
    if len(dataSet[0]) == 1:     #no more features
        return majorityCnt(classList)
    bestFeat = chooseBestFeatureToSplit(dataSet)     #best feature to split on
    bestFeatLabel = labels[bestFeat]     #name of the best feature
    myTree = {bestFeatLabel:{}}
    del(labels[bestFeat])     #remove the feature splitting on
    featValues = [example[bestFeat] for example in dataSet]     #list of values of the best feature
    uniqueVals = set(featValues)     #remove duplicates
    for value in uniqueVals:
        subLabels = labels[:]
        myTree[bestFeatLabel][value] = createTree(splitDataSet(dataSet, bestFeat, value),\
            subLabels)     #backtrace until stop by if statements
    return myTree

def classify(inputTree, featLabels, testVec):
    firstStr = list(inputTree.keys())[0]     #split feature
    secondDict = inputTree[firstStr]     #splitted results
    featIndex = featLabels.index(firstStr)     #index of split feature
    for key in secondDict.keys():     #value of split feature
        if testVec[featIndex] == key:     #testV has the same value with key
            if type(secondDict[key]).__name__ == 'dict':     #branch or leafnode
                classLabel = classify(secondDict[key], featLabels, testVec)     #traverse
            else:
                classLabel = secondDict[key]     #leafnode
    return classLabel

def storeTree(inputTree, filename):
    import pickle
    fw = open(filename, 'w')
    pickle.dump(inputTree, fw)
    fw.close()
    
def grabTree(filename):
    import pickle
    fr = open(filename)
    return pickle.load(fr)
